package com.xxkj.drugtraceability.net

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

/**
 * author: zhoujingjin
 * created on: 2022/2/28 10:01
 * description:
 */
class GsonConverterDataFactory private constructor(private val gson: Gson) : Converter.Factory() {
    override fun responseBodyConverter(
        type: Type, annotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<ResponseBody, *> {
        val adapter = gson.getAdapter(TypeToken.get(type))
        return GsonResponseDataConverter<Any>(gson, adapter, type)
    }

    override fun requestBodyConverter(
        type: Type,
        parameterAnnotations: Array<Annotation>,
        methodAnnotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<*,RequestBody> {
        val adapter = gson.getAdapter(TypeToken.get(type))
        return GsonRequestBodyDataConverter(gson, adapter)
    }

    companion object {
        //使用这个工厂方法可以从外部传入Gson对象，我们可以对这个Gson对象做很多配置
        //最常使用的静态工厂方法，使用默认的Gson实例
        @JvmOverloads
        fun create(
            gson: Gson = Gson()
        ): GsonConverterDataFactory {
            return GsonConverterDataFactory(gson)
        }
    }
}